<template>
  <div id="app">
    <el-card shadow="always">
      <el-form :inline="true" :model="userSearch" class="demo-form-inline">
<!--        <el-form-item label="学生id">-->
<!--          <el-input v-model="userSearch.id" placeholder="学生id"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="学生姓名">
          <el-input v-model="userSearch.name" placeholder="学生姓名"></el-input>
        </el-form-item>
        <el-form-item label="学生年龄">
          <el-input v-model="userSearch.age" placeholder="学生年龄"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="success" @click="add">添加</el-button>
          <el-button type="danger" @click="handleDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
    <el-table
        :data="userList"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          >
      </el-table-column>
      <el-table-column
          label="学号"
          align="center"
          prop="id">
      </el-table-column>
      <el-table-column
          label="姓名"
          align="center"
          prop="name">
      </el-table-column>
      <el-table-column
          label="年龄"
          align="center"
          prop="age">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
      {{user}}
      <el-form :model="user" :rules="rules" ref="ruleForm">
<!--        <el-form-item label="学生id" prop="id" :label-width="formLabelWidth">-->
<!--          <el-input v-model="TUser.id" autocomplete="off"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="学生姓名" prop="name" :label-width="formLabelWidth">
          <el-input v-model="user.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生年龄" prop="age" :label-width="formLabelWidth">
          <el-input v-model.number="user.age" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>

import userapi from "@/api/user";

export default {
  data() {
    // 自定义校验规则
    let checkAge = (rule, value, callback) => {
      if (value === '' || value == null) {
        return callback(new Error('年龄不能为空'))
      } else if (!Number.isInteger(value)) {
        return callback(new Error('年龄必须为数字值'))
      } else if (value < 1 || value > 200) {
        return callback(new Error('年龄必须在1-200之间'))
      } else {
        callback()
      }
    }

    return {
      userList: [],
      page:1, // 当前页的所有学生信息集合
      pageSize:5,
      total:100,
      userSearch:{},
      user:{},
      formLabelWidth:'100px',
      dialogFormVisible:false,
      title:'学生信息',
      multipleSelection:[],//数组，选中多项
      ids:[],//选中的学生

      rules: {
        // id: [
        //   { required: true, message: '请输入学生id', trigger: 'blur' },
        // ],
        name: [
          { required: true, message: '请输入学生姓名', trigger: 'blur' },
        ],
        age: [
          // { required: true, message: '请输入学生年龄', trigger: 'blur' },
          {validator : checkAge, trigger:'blur'}
        ],

      }

    }
  },

  created(){
    // this.findByPage()
    // this.search()
    // this.findUsers()
    this.search()
  },
  methods: {
  //    async findUsers(){
  // const {data:res} = await userapi.findUsers()
  //      console.log(res.data)
  //   this.userList = res.data.list
  //   },

    // async findByPage(){
    //   const {data:res} = await userapi.findByPage(this.page,this.pageSize)
    //   console.log(res)
    //   if (res.code === 200) {
    //     this.userList = res.data.u.rows
    //     this.total = res.data.u.total
    //   }
    // },
    async search(){
      const {data:res} = await userapi.search(this.page,this.pageSize,this.userSearch)
      console.log(res)
      if (res.code === 200) {
        this.userList = res.data.u.rows
        this.total = res.data.u.total
      }

    },
    //
    add(){
      //绑定标题
      this.title='学生信息'
      //清空学生信息
      this.user={}
      //弹出对话框
      this.dialogFormVisible=true
      this.dialogFormVisible=true;
    },

    saveUser(){
      this.$refs.ruleForm.validate(async valid=>{
        let url = "/user/add"
        let method="post"
        if(this.user.id){
          url = "/user/update"
          method="put"
        }
        if(valid){
         const{data:res}=await userapi.save(url,method,this.user)
          console.log("res:",res)
          if (res.code === 200) {
            this.$message({
              type:'success',
              message:res.message,
              onClose:() =>{
                this.dialogFormVisible=false
                this.search()
              }
            })
          }else{
            this.$message({
              type:'error',
              message:res.message
            })
          }
        }else {
          console.log("验证失败")
        }
      })

    },

    handleEdit(index,row){
      //绑定标题
      this.title='修改学生信息'
      //拿到行数据
      this.user=row
      //弹出对话框
      this.dialogFormVisible=true
      console.log(index,row)
    },
    handleDelete(index,row){
      this.ids=[];
      if(row){
        this.ids.push(row.id)
      }else {
        this.ids = this.multipleSelection.map(m => m.id)
      }
      this.$confirm(`是否真的要删除学号为${this.ids}的学生吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _this=this
        userapi.deleteUser(this.ids)
            .then(({data:res})=>{
              console.log("res:",res)
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  onClose: () => {
                    // 重新加载数据
                    _this.search()
                  }
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection)
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize=val
      this.search()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page=val
      this.search()
    }
  }
}

</script>

<style>
.el-card{
  width: 90%;
}
#app{
  display: flex;
  justify-content: center;
}
.el-pagination{
  margin-top: 20px;
  text-align: right;
}


</style>
